package database

import (
	"rbac-system/config"
	"rbac-system/models"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func InitDB() {
	dsn := config.AppConfig.Database.User + ":" +
		config.AppConfig.Database.Password + "@tcp(" +
		config.AppConfig.Database.Host + ":" +
		config.AppConfig.Database.Port + ")/" +
		config.AppConfig.Database.DBName + "?charset=utf8mb4&parseTime=True&loc=Local"

	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("连接数据库失败: " + err.Error())
	}

	// 自动迁移表结构
	err = DB.AutoMigrate(
		&models.User{},
		&models.Role{},
		&models.Permission{},
		&models.RolePermission{},
		&models.UserRole{},
	)
	if err != nil {
		panic("迁移表结构失败: " + err.Error())
	}

	// 初始化基础数据
	initBaseData()
}

func initBaseData() {
	// 创建超级管理员角色
	var adminRole models.Role
	DB.FirstOrCreate(&adminRole, models.Role{
		Name:        "超级管理员",
		Description: "系统超级管理员，拥有所有权限",
	})

	// 创建基础权限
	permissions := []models.Permission{
		{Name: "用户管理", Code: "user:manage", Description: "用户管理权限", Type: 1},
		{Name: "角色管理", Code: "role:manage", Description: "角色管理权限", Type: 1},
		{Name: "权限管理", Code: "permission:manage", Description: "权限管理权限", Type: 1},
	}

	for _, perm := range permissions {
		DB.FirstOrCreate(&perm, models.Permission{Code: perm.Code})
	}

	// 关联角色和权限
	DB.Model(&adminRole).Association("Permissions").Append(&permissions)
}
